<?php
/**
 * Created by PhpStorm.
 * User: Bruce
 * Date: 2020/5/19
 * Time: 19:48
 */function tree1($data,$p_id=0){
    $tree = [];
    foreach($data as $row){
        if($row['pid']==$p_id){
            $tmp = tree1($data,$row['id']);
            if($tmp){
                $row['child']=$tmp;
            }else{
                $row['child'] = [];
            }
            $tree[]=$row;
        }
        // var_dump($tree);
    }
    return $tree;
}

$list = [
    ['id'=> 8,'pid' => 0, 'name' => '北京'],
    ['id'=> 1,'pid' => 8, 'name' => '昌平'],
    ['id'=> 2,'pid' => 8, 'name' => '朝阳'],
    ['id'=> 3,'pid' => 8, 'name' => '延庆'],
    ['id'=> 4,'pid' => 1, 'name' => '天通苑'],
    ['id'=> 5,'pid' => 1, 'name' => '半截塔'],
    ['id'=> 6,'pid' => 3, 'name' => '延庆小区'],
    ['id'=> 7,'pid' => 0, 'name' => '山西'],
    ['id'=> 9,'pid' => 5, 'name' => '半截塔小卖部'],
];
echo "<pre>";
print_r(tree1($list,5));